<?php

namespace Home\Controller;


use Think\Controller;

class UserController extends Controller {
    /**
     * 用户登陆
     */
    public function login(){
        if(isset($_COOKIE['username'])) {
            echo "<script>window.location.href = './index.html';</script>";
        }
        $this->assign('title','用户登录');
        $this->display();
    }

    /**
     * 登陆验证
     */
    public function loginCheck(){
       session_start();
       $username=$_POST['username'];//手机号或邮箱
       $pwd=$_POST['password'];//密码
       $pwd.="sccdrz";//对密码进行加标记处理
       $password=md5($pwd);//对密码进行md5加密
        $week = $_POST['week'];
           $phoneReg="/^(13[0-9]|15[0|1|2|3|6|7|8|9]|18[0|2|3|5|6|7|8|9]|17[0])\d{8}$/";//电话正则
           $emailReg="/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/";//邮箱正则
           $res_p=preg_match($phoneReg,$username);//将用户输入来匹配电话正则
           $res_e=preg_match($emailReg,$username);//将用户输入来匹配邮箱正则
           //连接数据库进行账号、密码验证：
           $member=M('Member');//实例化会员表，数据表首字母须大写，否则无法完成自动验证

           //验证验证码对错
            $verify=strtolower($_POST['verify']);
            $ver=new \Think\Verify();
            if($ver->check($verify)){
                //用户用电话号码登陆
                if('1' == $res_p){//1表示匹配成功，0表示匹配失败
                    $condition['phone']=$username;
                    $result=$member->where($condition)->select();//数据库查询用户输入数据
                    if($result){
                        $condition['password']=$password;
                        $condition['_logic']='AND';
                        $res=$member->where($condition)->select();
                        if($res){
                            session(null);
                            $_SESSION['username']=$result[0]['username'];//将用户名存入SESSION，在其他页面都显示用户名，点击用户名可查询用户详细信息
                            //当用户名超出18位长度，进行处理
                            $NameLength = $_SESSION['username'];
                            if(strlen($NameLength) > 18) {
                                $NameLength = substr($NameLength,0,15).'...';
                            }
                            //使用cookies一周免登录
                            //当用户选择一周内免登录，cookie周期为一周
                            if($week == 'week') {
                                setcookie("username",$_SESSION['username'],time()+1*7*24*3600);
                                setcookie("ShortName",$NameLength,time()+1*7*24*3600);
                            }
                            //若用户没有选择,保存时间为10秒，仅用于测试
                            else{
                                setcookie("username",$_SESSION['username'],time()+10);
                                setcookie("ShortName",$NameLength,time()+10);
                            }
                            $last_login_time=time();//记录用户此次登陆时间
                            $last_login_ip=get_client_ip();//记录用户此次登陆ip
                            $data=array(
                                'last_login_time'=>$last_login_time,
                                'last_login_ip'=>$last_login_ip
                            );
                            $terms['phone']=$username;
                            $member->where($terms)->setField($data);//修改用户的最后登录时间和登录Ip
                            $member->where($terms)->setInc('login_times');//将用户的登陆次数 +1
                            echo "0";
                        }else{
                            echo "2";
                        }
                    }else{
                        echo "3";
                    }

                    //用户用邮箱登陆
                }elseif('1' == $res_e){//1表示匹配成功，0表示匹配失败
                    $condition['email']=$username;
                    $result=$member->where($condition)->select();//数据库查询用户输入数据
                    if($result){
                        $condition['password']=$password;
                        $condition['_logic']='AND';
                        $res=$member->where($condition)->select();
                        if($res){
                            session(null);
                            $_SESSION['username']=$result[0]['username'];//将用户名存入SESSION，在其他页面都显示用户名，点击用户名可查询用户详细信息
                            //当用户名超出18位长度，进行处理
                            $NameLength = $_SESSION['username'];
                            if(strlen($NameLength) > 18) {
                                $NameLength = substr($NameLength,0,15).'...';
                            }
                            //使用cookies一周免登录
                            //当用户选择一周内免登录，cookie周期为一周
                            if($week == 'week') {
                                setcookie("username",$_SESSION['username'],time()+1*7*24*3600);
                                setcookie("ShortName",$NameLength,time()+1*7*24*3600);
                            }
                            //若用户没有选择,保存时间为10秒，仅用于测试
                            else{
                                setcookie("username",$_SESSION['username'],time()+10);
                                setcookie("ShortName",$NameLength,time()+10);
                            }
                            $last_login_time=time();//记录用户此次登陆时间
                            $last_login_ip=get_client_ip();//记录用户此次登陆ip
                            $data=array(
                                'last_login_time'=>$last_login_time,
                                'last_login_ip'=>$last_login_ip
                            );
                            $terms['email']=$username;
                            $member->where($terms)->setField($data);//修改用户的最后登录时间和登录Ip
                            $member->where($terms)->setInc('login_times');//将用户的登陆次数 +1
                            echo "0";
                        }else{
                            echo "2";
                        }
                    }else{
                        echo "4";
                    }
                }else{
                    echo "1";
                }
            }else{
                echo "5";
            }
   }

    /**
     * 会员简要注册第一步
     */
    public function mstreg(){
        $this->assign('title','注册');
        $this->display();
    }



    /**
     * 会员注册第一步验证验证
     */
    public function mstregCheck(){
        session_start();
        //$phone=$_POST['username'];//获取用户输入的手机号码
        $email=$_POST['username'];//获取用户输入的邮箱
        $verify=$_POST['verify'];//获取用户输入的验证码
        $member=M('Member');//实例化会员表，数据表首字母须大写，否则无法完成自动验证
        //$condition['phone']=$phone;
        //$result=$member->where($condition)->select();//检查用户手机号是否被注册
        $condition['email']=$email;
        $result=$member->where($condition)->select();//检查用户邮箱是否被注册
        if( preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/",$email) ){//邮箱格式匹配
            if(!$result){//未被注册
                //将用户输入的验证码与短信平台提供的验证码作对比
                $random=$_SESSION['verify'];
                if($verify === $random){//验证码匹配成功
                    //将电话号码存入SESSSION
                    //$_SESSION['phone']=$phone;
                    $_SESSION['email']=$email;
                    echo "0";
                }else{//验证码匹配失败
                    echo "1";
                }
            }else{//已被注册
                echo "2";
            }
        }else{//邮箱格式不匹配
            echo "3";
        }

    }

    /**
     * 会员简要注册第二步
     */
    public function mndreg(){
        session_start();
        //判断是否通过注册第一步
        if( isset($_SESSION['email']) && preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/",$_SESSION['email']) ){//通过
            //判定验证码是否有效
            if($_SESSION['verify']){//验证码有效
                $this->assign('title','注册');
                $this->display();
            }else{//验证码失效
                echo "<script language='JavaScript'>alert('验证码已过期');</script>";
                redirect(U('/mstreg'),0,"跳转中...");
            }
        }else{
            session(null);
            redirect(U('/mstreg'),0,"跳转中...");
        }
    }

    /**
     * 会员注册第二步验证验证
     */
    public function mndregCheck(){
        session_start();
        //然后判断是否通过了注册第一步
        if( isset($_SESSION['email']) && preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/",$_SESSION['email']) ){//通过
            //首先判定验证码是否有效
            if($_SESSION['verify']){//验证码有效
                $phone=$_POST['mobile'];//获取用户输入的邮箱
                $password=$_POST['password'];//获取用户输入的密码
                $conPassword=$_POST['conPassword'];//获取用户第二次输入的密码
                $verify=$_POST['verify'];//获取用户输入的验证码
                //验证邮箱格式是否有误
                if(preg_match("/^(13[0-9]|15[0|1|2|3|6|7|8|9]|18[0|2|3|5|6|7|8|9]|17[0])\d{8}$/",$phone)){//格式正确
                    //检查用户输入的邮箱是否被注册
                    $member=M('Member');//实例化会员表，数据表首字母须大写，否则无法完成自动验证
                    $condition['phone']=$phone;
                    $result=$member->where($condition)->select();
                    if(!$result){//手机号未被注册，可用
                        //验证码验证：
                        $verify=strtolower($verify);//将验证码全部转为小写
                        $ver=new \Think\Verify();
                        if($ver->check($verify)){//验证码正确
                            if( preg_match("/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,18}$/",$password) ){//密码长度验证
                                //检查用户两次输入的密码是否一致
                                if($password == $conPassword){//密码一致
                                    //将用户的资料录入数据
                                    $password.="sccdrz";//对密码进行加标记处理
                                    $reg_time=time();//获取用户注册时间
                                    $reg_ip=get_client_ip();//获取用户注册客户端Ip
                                    $data=array(
                                        'username'=>$phone,
                                        'email'=>$_SESSION['email'],
                                        'phone'=>$phone,
                                        'password'=>md5($password),
                                        'reg_time'=>$reg_time,
                                        'reg_ip'=>$reg_ip,
                                        'last_modify_time'=>time(),
                                    );
                                    $result=$member->data($data)->add();
                                    if($result){//录入数据成功
                                        session(null);
                                        $_SESSION['phone']=$data['phone'];
                                        echo "0";
                                    }else{//录入数据失败
                                        echo "1";
                                    }

                                }else{//密码不一致
                                    echo "2";
                                }
                            }else{//密码长度过短或过长
                                echo "8";
                            }
                        }else{//验证码错误
                            echo "3";
                        }

                    }else{//手机号已被注册
                        echo "4";
                    }

                }else{//格式错误
                    echo "5";
                }

            }else{//验证码失效
                echo "7";
            }

        }else{//未通过
            echo "6";
        }
    }

    /**
     * 提示页面
     */
    public function tips(){
        session_start();
        /**
         * 判断是 会员注册成功 还是 店主注册成功
         */
        if(isset($_SESSION['success']) && 'shopkeeper'==$_SESSION['success']){//店主注册成功
            $time=time()+'172800';
            $time=date('Y-m-d H:i:s',$time);
            $this->assign('tips','材料提交成功。审核最晚在'.$time.'前完成，请耐心等待');
            $this->assign('title','提示');
            $this->display();
        }elseif($_SESSION['phone']){
            $member=M('Member');
            $condition['phone']=$_SESSION['phone'];
            $result=$member->where($condition)->select();
            if($result){
                session(null);
                $_SESSION['username']=$result[0]['username'];//记录会员通过初步注册的用户名
                $NameLength = $_SESSION['username'];
                if(strlen($NameLength) > 18) {
                    $NameLength = substr($NameLength,0,15).'...';
                }
                setcookie("username",$_SESSION['username'],time()*30*60);
                setcookie("ShortName",$NameLength,time()*30*60);
                $_SESSION['email']=$result[0]['email'];//记录会员通过初步注册的用户名
                $_SESSION['success']='member';//记录会员通过初步注册标记
                $this->assign('tips','恭喜您！成功通过初步注册');
                $this->assign('title','提示');
                $this->display();
            }else{
                session(null); //清空所有session信息
                redirect(U('/tips'), 0, '跳转中...');
            }
        }elseif($_SESSION['nickname']){//会员完善资料成功
            $this->assign('tips','恭喜您！填写资料完成,成功注册为会员');
            $this->assign('title','提示');
            $this->display();
        }else{//非法操作
            session(null); //清空所有session信息
            $this->assign('tips','不好意思，好像哪里出错了！');
            $this->assign('title','提示');
            $this->display();
        }
    }


    /**
     * 店主注册
     */
    public function kreg(){
        session_start();
        header("Content-type:text/html; charset=utf-8");
        //判断用户是否注册成为会员，或者会员已登录（只有在会员注册成功后或者会员登录的情况下才能进入店主注册页面）
        if( $_COOKIE['username']){//会员是登录状态，或者刚刚注册
            $member=M('Member');
            $shopkeeper=M('Shopkeeper');
            $condition['username']=$_COOKIE['username'];
            $result=$member->where($condition)->select();
            if($result){
                $email=$result[0]['email'];//对应会员邮箱
                $phone=$result[0]['phone'];//对应会员电话号码
                $terms['email']=$email;
                $terms['phone']=$phone;
                $terms['_logic']="OR";
                $res=$shopkeeper->where($terms)->select();
                if($res){
                    echo "<script>alert('店主已注册，请直接登录或重新选择账号注册')</script>";
                    echo "<script>window.history.go(-1)</script>";
                }else{
                    $this->assign('title','店主注册');
                    $this->display();
                }
            }else{
                echo "<script>alert('请求超时,请重试')</script>";
                redirect(U('/index'),0,"跳转中...");
            }
        }else{//会员未注册也未登陆
            echo "<script language='JavaScript'>alert('访问被拒绝')</script>";
            redirect(U('/mstreg'),0,"跳转中...");
        }
    }

    /**
     * 店主注册验证
     */
    public function kregCheck(){
        session_start();
        header("Content-type:text/html; charset=utf-8");
        $member=M('Member');
        $shopkeeper=M('Shopkeeper');//实例化店主表，数据表首字母须大写，否则无法完成自动验证
            $email="";
            $phone="";
            $password="";
            $condition['username']=$_COOKIE['username'];
            $result=$member->where($condition)->select();
            if($result){
                $email.=$result[0]['email'];//对应会员邮箱
                $phone.=$result[0]['phone'];//对应会员电话号码
                $password.=$result[0]['password'];//对应会员密码
                $terms['email']=$email;
                $terms['phone']=$phone;
                $terms['_logic']="OR";
                $res=$shopkeeper->where($terms)->select();
                if($res){
                    echo "<script>alert('店主已注册，请直接登录或重新选择账号注册')</script>";
                    echo "<script>window.history.go(-1)</script>";
                }else{
                    //用thinkPHP的 I() 函数对用户的输入进行 htmlspecialchars[默认处理方法] 处理，防止SQL注入
                    $realname=I('post.realname');//店主真实姓名
                    $gender=I('post.gender');//店主性别
                    $age=I('post.age');//店主年龄
                    $qq=I('post.qq');//店主联系QQ
                    $address=I('post.address');//店主详细住址
                    $pay_account=I('post.pay_account');//店主支付宝账号
                    $idcard=I('post.idCard');//店主身份证号码
                    $photo_path="";//健康照路径
                    $photo_front_path="";//身份证正面照路径
                    $photo_back_path="";//身份证背面照路径
                    /**
                     * 照片上传操作
                     */
                    /*设定上传目录*/
                    $dest_dir="./Public/images/upload";


                    /*获取上传文件信息*/
                    $photo=$_FILES['photo'];//健康证照
                    $id_photo_front=$_FILES['id_photo_front'];//身份证正面照
                    $id_photo_back=$_FILES['id_photo_back'];//身份证背面照
                    /**
                     * 获取文件后缀名函数
                     * @param $file 传入的文件
                     * @return string 返回文件的后缀名
                     */
                    function fileext($file){
                        return substr(strrchr($file,'.'),1);
                    }

                    /**
                     * 规范文件大小函数
                     * @param $size 文件规定大小
                     * @return string   返回实际文件大小
                     */
                    function formatsize($size){
                        if($size<1024){
                            return $size.'bytes';
                        }elseif($size<1024*1024){
                            return number_format($size/1024,2).'Kb';
                        }elseif($size<1024*1024*1024){
                            return number_format($size/(1024*1024),2).'M';
                        }else{
                            return "文件太大了";
                        }
                    }
                    /*设置允许上传照片的类型*/
                    $type=array('jpg','jpeg','png','bmp','gif');
                    /*判断上传文件类型*/
                    if(!in_array(strtolower(fileext($_FILES['id_photo_front']['name'])),$type) || !in_array(strtolower(fileext($_FILES['photo']['name'])),$type) || !in_array(strtolower(fileext($_FILES['id_photo_back']['name'])),$type)){
                        $text=implode(',',$type);
                        die("对不起，您只能上传以下类型的文件".$text."<br>") ;
                    }else{
                        $type_photo=substr($photo['type'],6);//健康照片类型
                        $type_photo_front=substr($id_photo_front['type'],6);//身份证正面照片类型
                        $type_photo_back=substr($id_photo_back['type'],6);//身份证背面照片类型
                        /*设置上传文件的文件名为：日期格式+随机数*/
                        $dest_photo=$dest_dir.'/'.date("YmdHis",time()).rand().'.'.$type_photo;
                        $dest_photo_front=$dest_dir.'/'.date("YmdHis",time()).rand().'.'.$type_photo_front;
                        $dest_photo_back=$dest_dir.'/'.date("YmdHis",time()).rand().'.'.$type_photo_back;
                        /*移动文件到指定目录*/
                        $state_photo=move_uploaded_file($photo['tmp_name'],$dest_photo);
                        $state_photo_front=move_uploaded_file($id_photo_front['tmp_name'],$dest_photo_front);
                        $state_photo_back=move_uploaded_file($id_photo_back['tmp_name'],$dest_photo_back);
                        if( $state_photo && $state_photo_front && $state_photo_back ){
                            $photo_path.=substr($dest_photo,'1');//健康照最终地址
                            $photo_front_path.=substr($dest_photo_front,'1');//身份证正面照最终地址
                            $photo_back_path.=substr($dest_photo_back,'1');//身份证背面照最终地址
                            $reg_ip=get_client_ip();//注册ip
                            $reg_time=time();//注册时间
                            $last_modify_time=time();//最后修改时间

                            /*将数据存入数据库*/
                            $data['name']=$realname;
                            $data['gender']=$gender;
                            $data['age']=$age;
                            $data['qq']=$qq;
                            $data['address']=$address;
                            $data['IDcard']=$idcard;
                            $data['photo']=$photo_path;
                            $data['id_photo_front']=$photo_front_path;
                            $data['id_photo_back']=$photo_back_path;
                            $data['reg_ip']=$reg_ip;
                            $data['reg_time']=$reg_time;
                            $data['last_modify_time']=$last_modify_time;
                            $data['email']=$email;
                            $data['phone']=$phone;
                            $data['password']=$password;
                            $data['pay_account']=$pay_account;
                            $res=$shopkeeper->data($data)->add();
                            if($res){
                                $term['email']=$email;
                                $shopkeeper->where($term)->setInc("login_times");
                                //录入成功后跳转到提示页面
                                session(null);
                                $_SESSION['success']="shopkeeper";//店主注册成功，记录SESSION
                                redirect(U('/tips'),'0','跳转中...');
                            }else{
                                exit( $shopkeeper->getError() );
                            }

                        }else{
                            /*处理健康照错误信息*/
                            switch($photo['error']){
                                case 1:
                                    die("健康照大小超出php.in中max_upload_filesize限制<br>");
                                case 2:
                                    die("健康照大小超出 MAX_FILE_SIZE 限制<br>");
                                case 3:
                                    die("健康照仅部分被上传<br>");
                                case 4:
                                    die("健康照没有被上传<br>");
                                case 5:
                                    die("健康照临时文件不存在<br>");
                                case 6:
                                    die("健康照写入失败<br>");
                            }
                            /*处理身份证正面错误信息*/
                            switch($id_photo_front['error']){
                                case 1:
                                    die("身份证正面照大小超出php.in中max_upload_filesize限制<br>");
                                case 2:
                                    die("身份证正面照大小超出 MAX_FILE_SIZE 限制<br>");
                                case 3:
                                    die("身份证正面照仅部分被上传<br>");
                                case 4:
                                    die("身份证正面照没有被上传<br>");
                                case 5:
                                    die("身份证正面照临时文件不存在<br>");
                                case 6:
                                    die("身份证正面照写入失败<br>");
                            }
                            /*处理身份证背面错误信息*/
                            switch($id_photo_back['error']){
                                case 1:
                                    die("身份证背面照大小超出php.in中max_upload_filesize限制<br>");
                                case 2:
                                    die("身份证背面照大小超出 MAX_FILE_SIZE 限制<br>");
                                case 3:
                                    die("身份证背面照仅部分被上传<br>");
                                case 4:
                                    die("身份证背面照没有被上传<br>");
                                case 5:
                                    die("身份证背面照临时文件不存在<br>");
                                case 6:
                                    die("身份证背面照写入失败<br>");
                            }
                        }
                    }

                }

            }else{//SESSION出错
                echo "<script language='JavaScript'>alert('操作超时')</script>";
                redirect(U('/login'),0,"跳转中...");
            }

    }


    /**
     * 用户详细资料
     */
    public  function detail(){
        session_start();
        if($_COOKIE['username']){//用户已登录
            $this->display();
        }else{//用户未登录
            echo "<script language='JavaScript'>alert('请先登录')</script>";
            redirect(U('/login'),0,"跳转中...");
        }
    }




    /**
     * 普通用户注册
     */
    public function ureg() {
        session_start();
        //判断用户是否通过初步注册
        if($_SESSION['username']){
            $member=M('Member');
            $condition['username']=$_SESSION['username'];
            $result=$member->where($condition)->select();
            if($result){
                $this->assign("title","会员注册");
                $this->display();
            }else{
                session(null);
                redirect(U('/tips'),0,"跳转中...");
            }
        }else{
            session(null);
            redirect(U('/tips'),0,"跳转中...");
        }
    }

    //普通用户信息
    public function userInfo() {
        header("Content-Type: text/html; charset=UTF-8");
        session_start();
        $nickname = $_POST['nickname'];			//用户昵称
        $name = $_POST['xm'];					//用户姓名
        $sex = $_POST['sex'];					//用户性别
        $age = $_POST['age'];					//用户年龄
        $qq = $_POST['qq'];						//用户QQ
        $address = $_POST['address'];			//用户详细地址

        $User = M("Userinfo");
        $data['username'] = $nickname;
        $data['name'] = $name;
        $data['gender'] = $sex;
        $data['age'] = $age;
        $data['qq'] = $qq;
        $data['address'] = $address;

        //当用户点提交时将用户基本信息写入数据库保存
        if($_SESSION['username']) {
            $term['phone']=$_SESSION['username'];
            $member = M("Member");
            $result=$member->where($term)->select();
            if($result){
                $terms['username']=$nickname;
                $results=$User->where($terms)->select();
                if($results){
                    echo "6";
                }else{
                    $result = $User->data($data)->add();
                    if($result) {
                        if($_SESSION['email']){
                            $condition['email']=$_SESSION['email'];
                            $res=$member->where($condition)->setField('username',$nickname);
                            if($res){
                                session(null);
                                $_SESSION['nickname']=$data['username'];
                                $_SESSION['username']=$_SESSION['nickname'];
                                $NameLength = $_SESSION['username'];
                                if(strlen($NameLength) > 18) {
                                    $NameLength = substr($NameLength,0,15).'...';
                                }
                                setcookie("username",$_SESSION['username'],time()+10);
                                setcookie("ShortName",$NameLength,time()+10);
                                echo "0";
                            }else{
                                echo "1";
                            }
                        }else{
                            session(null);
                            echo "2";
                        }
                    }else{
                        echo "3";
                    }
                }
            }else{
                session(null);
                echo "4";
            }

        }else{
            session(null);
            echo "5";
        }
    }

}

